package cn.vendpay.com.service.impl;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 库存回调管理器
 * @author Eleven
 */
@Component
public class InventoryCallbackManager {

    private final ConcurrentMap<String, CompletableFuture<Map<String, Object>>> FUTURES = new ConcurrentHashMap<>();

    /**
     * 创建并注册 future，超时后会自动清理
     * @param requestId 唯一 id (correlationId)
     * @param timeoutMs 超时毫秒
     */
    public CompletableFuture<Map<String, Object>> createFuture(String requestId, long timeoutMs) {
        CompletableFuture<Map<String, Object>> future = new CompletableFuture<>();
        FUTURES.put(requestId, future);

        // 超时清理
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(() -> {
            CompletableFuture<Map<String, Object>> f = FUTURES.remove(requestId);
            if (f != null && !f.isDone()) {
                f.completeExceptionally(new TimeoutException("Callback timeout"));
            }
            scheduler.shutdown();
        }, timeoutMs, TimeUnit.MILLISECONDS);

        // 保证 future 完成后从 map 移除
        future.whenComplete((r, e) -> FUTURES.remove(requestId));
        return future;
    }

    public void complete(String requestId, Map<String, Object> payload) {
        CompletableFuture<Map<String, Object>> f = FUTURES.remove(requestId);
        if (f != null) {
            f.complete(payload);
        }
    }
}
